﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void ShowMessage(string msgStr)
        {
            txtLog.AppendText(msgStr + "\r\n");
        }
        private Socket socketSend;
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                //创建通信对象
                socketSend=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
                IPAddress ip = IPAddress.Parse(txtServer.Text);
                IPEndPoint point=new IPEndPoint(ip,Convert.ToInt32(txtPort.Text));

                //获取连接的远程服务器应用程序的IP地址和端口号
                socketSend.Connect(point);
                ShowMessage("连接"+ip+":"+txtPort.Text.Trim()+"成功！");

                //开启新线程不停接受服务端发送过来的消息
                Thread th = new Thread(Receive);
                th.IsBackground = true;
                th.Start();
            }
            catch 
            {
                MessageBox.Show("网络连接错误，请重新连入！！");
                
            }
        }
        /// <summary>
        /// 给服务端发送文本
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            //如果socket未连接，则提出
            if (socketSend == null || !socketSend.Connected)
            {
                MessageBox.Show("网络连接错误，请重新连入！！");
                return;
                
            }

            try
            {
                var str = txtMsg.Text;
                byte[] buffer = Encoding.UTF8.GetBytes(str);
                socketSend.Send(buffer);
                //发送成功后清空文本框
                txtMsg.Text = "";
            }
            catch
            {
                MessageBox.Show("网络连接错误，请重新连入！！");
            }

        }
        /// <summary>
        /// 不停接受服务器端的消息
        /// </summary>
        private void Receive()
        {

            while (true)
            {
                byte[] buffer=new byte[1024*1024*5];
                int r = socketSend.Receive(buffer);
                if(r==0)
                    break;
                //发送文字
                if (buffer[0] == 0)
                {
                    string str = Encoding.UTF8.GetString(buffer, 1, r - 1);
                    ShowMessage(socketSend.RemoteEndPoint+":"+str);
                }

                //发送文件
                else if (buffer[0] == 1)
                {
                    var dialog=new SaveFileDialog();
                    dialog.InitialDirectory = @"F:\B";
                    dialog.Title = "请选择要保存的文件";
                    dialog.Filter="所有文件|*.*";
                    dialog.ShowDialog(this);

                    var path = dialog.FileName;
                    if (string.IsNullOrEmpty(path))
                    {
                        MessageBox.Show("请选择保存文件夹！");
                        return;
                    }

                    try
                    {
                        using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            fsWrite.Write(buffer, 1, r - 1);
                        }
                        ShowMessage(socketSend.RemoteEndPoint + ":文件发送成功！");
                    }
                    catch
                    {
                        MessageBox.Show("网络访问错误，请重试！");
                        ShowMessage(socketSend.RemoteEndPoint + ":文件发送失败！");
                    }
                    

                }
                //发送震动
                else if (buffer[0] == 2)
                {
                    Shake();
                }
                else
                {
                    //其他的发送消息类型
                }
            }
           
        }
        /// <summary>
        /// 窗体震动ing
        /// </summary>
        private void Shake()
        {
            Random ran = new Random((int)DateTime.Now.Ticks);

            Point point = this.Location;

            for (int i = 0; i < 40; i++)
            {
                this.Location = new Point(point.X + ran.Next(8) - 4, point.Y + ran.Next(8) - 4);

                Thread.Sleep(15);

                this.Location = point;

                Thread.Sleep(15);

            }

            ////原窗体的X坐标
            //var x = this.Location.X;
            //var y = this.Location.Y;
            ////上下移动500次
            //for (int i = 0; i < 500; i++)
            //{
            //    this.Location = new Point(x - 20, y - 20);
            //    this.Location = new Point(x + 20, y + 20);
            //}
            ////位移完成后，回到原坐标
            //this.Location=new Point(x,y);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }
    }
}
